package io.vov.vitamio.tvpaser;

import io.vov.vitamio.entity.TVProgram;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableRow;
import org.htmlparser.util.NodeList;

/**
 * 在线视频
 * 
 * @author lichuan
 */
public class OnlineTVParser {

	/**
	 * 此服务要收费
	 */
	@Deprecated
	static final String TV_PROGRAME_URL = "http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx";

	static final String TV_PROGRAME_URL2 = "http://m.tvmao.com/program";

	private static OnlineTVParser mOnlineTVParser = null;

	private OnlineTVParser() {
	}

	public static OnlineTVParser getInstance() {

		if (mOnlineTVParser == null) {

			mOnlineTVParser = new OnlineTVParser();

		}

		return mOnlineTVParser;

	}

	public void getTVPrograms() {
		try {
			// batchOnlineTV2();
			// batchOnlineTV3();
			List<TVProgram> tvPrograms = getTVProgramList("ICABLEENT-CCTV4",
					new Date());
			for (int i = 0; i < tvPrograms.size(); i++) {
				System.out.println(tvPrograms.get(i));
			}
			Date currentDate = new Date();
			// currentDate.setDate(currentDate.getDate()+1);
			// currentDate.setHours(23);
			// currentDate.setMinutes(59);
			System.err.println("当前正在播放: "
					+ getCurrentTVProgram(tvPrograms, currentDate));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * 从tvmao网站读取电视节目单
	 * 
	 * @param source_code
	 *            电视台source_code节点值
	 * @param date
	 *            日期,如空则默认当天日期
	 * @return
	 */
	public List<TVProgram> getTVProgramList(String source_code, Date date) {
		List<TVProgram> tvPrograms = new ArrayList<TVProgram>();
		try {
			if (date == null) {
				date = new Date();
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
			day_of_week = day_of_week - 1 == 0 ? 7 : day_of_week - 1;
			SimpleDateFormat simpleDateParser = new SimpleDateFormat(
					"yyyy-MM-dd");
			String dateStr = simpleDateParser.format(date);

			String request_url = TV_PROGRAME_URL2 + "/" + source_code + "-w"
					+ day_of_week + ".html";
			// System.out.println("request_url: " + request_url );
			String response = HTTPUtility.openUrl(request_url);
			// System.out.println(response);
			response = response.replaceAll("\n", "");
			Pattern pattern = Pattern.compile("<table(.*?)</table>");
			Matcher matcher = pattern.matcher(response);
			if (matcher.find()) {
				String tidy_response = matcher.group();
				// System.out.println("tidy_response: " + tidy_response );
				Parser parser = Parser.createParser(tidy_response, "UTF-8");
				NodeList list = parser.parse(new TagNameFilter("tr"));
				final int size = list.size();
				for (int i = 1; i < size; i++) {
					TableRow tableRow = (TableRow) list.elementAt(i);
					if (tableRow.getChildCount() < 2) {
						continue;
					}
					TVProgram tvProgram = new TVProgram();
					tvProgram.setTvCode(source_code);
					tvProgram.setPlayTime( dateStr + " " + tableRow.getChild(
							0).toPlainTextString() +":00" );
					tvProgram
							.setTitle(tableRow.getChild(1).toPlainTextString());
					tvPrograms.add(tvProgram);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return tvPrograms;
	}

	/**
	 * 得到当前正在播放的电视节目
	 * 
	 * @param tvPrograms
	 *            电视节目列表
	 * @param currentDate
	 *            传入的指定时间，如果为空则默认当前时间
	 * @return
	 */
	public TVProgram getCurrentTVProgram(List<TVProgram> tvPrograms,
			Date currentDate) {
		if (StringUtil.isNull(tvPrograms)) {
			return null;
		}
		try {
			if (currentDate == null) {
				currentDate = new Date();
			}
			SimpleDateFormat simpleDateParser = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			
			final int size = tvPrograms.size();
			for (int i = 0; i < size; i++) {
				Date playTime = simpleDateParser.parse(tvPrograms.get(i)
						.getPlayTime());
				if (!currentDate.before(playTime)
						&& ((i < size - 1 && currentDate
								.before(simpleDateParser.parse(tvPrograms.get(
										i + 1).getPlayTime()))) || (i == size - 1 && currentDate
								.getDay() == playTime.getDay()))) {
					return tvPrograms.get(i);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	// /***
	// * 整理数据
	// */
	// private static void batchOnlineTV3(){
	// try {
	// XmlReaderHelper.getAllVideos3(new FileInputStream(new
	// File("F:\\CVSROOT\\Android\\机顶盒项目\\online.xml")));
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	/**
	 * 批处理在线视频地址,与webxml.com服务接口id对应
	 */
	// private static void batchOnlineTV2(){
	// Logger logger = Logger.getLogger(OnlineTVParser.class);
	// LinkedHashMap<String, String> tvChannelMaps = new LinkedHashMap<String,
	// String>();
	// int end_cont = 0;
	// try {
	// List<String> tvParams = new ArrayList<String>();
	//
	// //step1:解析目标网页,把地区分类读取到
	// String request_url = TV_PROGRAME_URL2 + "/playing";
	// String response = HTTPUtility.openUrl(request_url);
	// // System.out.println("response: " + response);
	// // Pattern pattern =
	// Pattern.compile("(<select(\\s|\\S)*</select></form>){1,2}?");
	// Pattern pattern = Pattern.compile("<select(.*?)</select></form>");
	// Matcher matcher = pattern.matcher(response);
	// if (matcher.find()) {
	// String tidy_response = matcher.group();
	// Parser parser = Parser.createParser(tidy_response, "UTF-8");
	// NodeList list = parser.parse(new TagNameFilter("option"));
	// if(list!= null && list.size() > 0){
	// for (int i = 0; i < list.size(); i++) {
	// TagNode option = (TagNode) list.elementAt(i);
	// System.out.println("省份: " + option.toPlainTextString() + "	key: " +
	// option.getAttribute("value"));
	// tvParams.add(option.getAttribute("value"));
	// }
	// }
	// }
	//
	// if(tvParams.size() == 0){
	// logger.error("解析地区参数出错,未找到节点!");
	// return;
	// }
	//
	// //step: 根据取得地区参数，循环抓取电视台
	// final int size = tvParams.size();
	// for (int i = 0; i < size + 1; i++) {
	// List<NameValuePair> httpParams = null;
	// if(i == size){
	// request_url= TV_PROGRAME_URL2 + "/playing/satellite/";
	// }else{
	// request_url= TV_PROGRAME_URL2 + "/playing";
	// httpParams = new ArrayList<NameValuePair>();
	// httpParams.add(new BasicNameValuePair("prov", tvParams.get(i)));
	// }
	// for (int j = 0; j < 3; j++) {
	// try {
	// if(httpParams == null){
	// response = HTTPUtility.openUrl(request_url);
	// }else{
	// response = HTTPUtility.openUrl(request_url, httpParams);
	// }
	// break;
	// } catch (Exception e) {
	// if(j == 2){
	// throw e;
	// }
	// e.printStackTrace();
	// }
	// Thread.sleep(1000);
	// }
	//
	// // System.out.println("response: " + response);
	//
	// pattern = Pattern.compile("<table(.*?)</table>");
	// matcher = pattern.matcher(response);
	// if (matcher.find()) {
	// String tidy_response = matcher.group();
	// Parser parser = Parser.createParser(tidy_response, "UTF-8");
	// NodeList list = parser.parse(new HasAttributeFilter("class","chnl"));
	// if (list != null && list.size() > 0) {
	// final int asize = list.size();
	// for (int j = 0; j < asize; j++) {
	// LinkTag linkTag = (LinkTag) list.elementAt(j).getChildren().elementAt(0);
	// //logger.debug("tv: \"" + linkTag.toPlainTextString() + "\",	link: \"" +
	// linkTag.getLink() +"\"");
	// String tv_code = linkTag.getLink();
	// tv_code = tv_code.substring(tv_code.lastIndexOf("/") + 1);
	// tv_code = tv_code.substring(0, tv_code.lastIndexOf("-"));
	// logger.warn(linkTag.toPlainTextString() + " | " + tv_code);
	// tvChannelMaps.put(linkTag.toPlainTextString(), tv_code);
	// }
	// }
	// }
	// end_cont = i;
	// Thread.sleep(500);
	// }
	//
	//
	// } catch (Exception e) {
	// // TODO: handle exception
	// e.printStackTrace();
	// }finally{
	// System.err.println("解析结束，解析到位置: " + end_cont + "	电视台数量: " +
	// tvChannelMaps.size());
	// }
	// }

	/**
	 * 批处理在线视频地址,与webxml.com服务接口id对应
	 */
	// private static void batchOnlineTV(){
	// try {
	// //step1: 读取所有电视台
	// XmlReaderHelper.getAllVideos2(new FileInputStream(new
	// File("F:\\CVSROOT\\Android\\机顶盒项目\\online.xml")));
	//
	// // for (int i = 0; i < size; i++) {
	// // System.out.println("videos: " + onlineList.get(i));
	// // }
	//
	// } catch (Exception e) {
	// // TODO: handle exception
	// e.printStackTrace();
	// }
	// }

	/**
	 * 从http://webservice.webxml.com.cn服务抓取单个频道的节目单
	 * 
	 * @param theTVchannelID
	 *            频道ID
	 * @param theDate
	 *            日期（yyyy-MM-dd，如：2007-07-02，空则默认当天）
	 * @param userID
	 *            商业用户ID（String 免费用户不需要）
	 * @return
	 * @throws Exception
	 */
	public static List<TVProgram> getTVprogramDateSet(String theTVchannelID,
			String theDate, String userID) throws Exception {
		List<TVProgram> tvprogramList = new ArrayList<TVProgram>();
		List<NameValuePair> httpParams = new ArrayList<NameValuePair>();
		httpParams
				.add(new BasicNameValuePair("theTVchannelID", theTVchannelID));
		httpParams.add(new BasicNameValuePair("theDate", theDate));
		httpParams.add(new BasicNameValuePair("userID", userID));
		String response = HTTPUtility.openUrl(TV_PROGRAME_URL
				+ "/getTVprogramDateSet", httpParams);
		// System.out.println("response: " + response);
		if (response != null && response.length() > 0) {
			tvprogramList = TVProgramReaderHelper
					.getTVProgramList(new ByteArrayInputStream(response
							.getBytes()));
		}
		return tvprogramList;
	}
}
